package com.example.demospringboot.netty.custom;

import com.alibaba.fastjson.JSON;
import com.example.demospringboot.netty.custom.ecodc.ByteToComPackDecoder;
import com.example.demospringboot.netty.custom.ecodc.ComPackToByteEncoder;
import com.example.demospringboot.netty.custom.handler.ClientChannelHandler;
import com.example.demospringboot.netty.custom.initializer.ClientChannelInitializer;
import com.example.demospringboot.netty.custom.procotol.ComPack;
import com.example.demospringboot.netty.http.Client;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;

import java.util.concurrent.TimeUnit;

/**
 * @author chenlei
 * @date 2020/1/16
 * @description
 **/
public class TcpClient {

    EventLoopGroup workerGroup;

    Bootstrap client;

    public TcpClient() {
        this.workerGroup = new NioEventLoopGroup();
        this.client = new Bootstrap();
        client.group(workerGroup);
        client.channel(NioSocketChannel.class);
        client.option(ChannelOption.TCP_NODELAY, true);
        client.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 60000);
        client.handler(new ClientChannelInitializer());
    }

    public ComPack send(){

        ClientChannelHandler clientChannelHandler = new ClientChannelHandler();
        try {
            ChannelFuture f = client.connect("127.0.0.1",8090).sync();
            Channel ch = f.channel();
            {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new ComPackToByteEncoder());
                pipeline.addLast(new ReadTimeoutHandler(5000, TimeUnit.MILLISECONDS));
                pipeline.addLast(new ByteToComPackDecoder());
                pipeline.addLast(clientChannelHandler);
            }
            ComPack req = new ComPack();
            ch.writeAndFlush(req).sync();
            ch.closeFuture().sync();
        }catch(Exception e) {
            e.printStackTrace();
        }
        return clientChannelHandler.getResponse();
    }

    public static void main(String[] args) {
        TcpClient client = new TcpClient();
        for (int i = 0; i < 10; i++) {
            client.send();
        }
    }
}
